package mwa.cs.rc.ctrl;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import mwa.cs.dao.AddressDAO;
import mwa.cs.dao.CustomerDAO;
import mwa.cs.dao.RcTransDDAO;
import mwa.cs.dao.RcTransMDAO;
import mwa.cs.database.Database;
import mwa.cs.util.JDate;

/**
 * Servlet implementation class CS55001Srvl
 */
public class CS55001Srvl extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private int vnSiteId;
	private int vnUserId;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public CS55001Srvl() {
		super();
		// TODO Auto-generated constructor stub
	}

	public void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/JSON");
		vnSiteId = Integer.parseInt(request.getSession().getAttribute("site_id").toString());
		if (request.getParameter("process_type").equals("getDataTable")) {
			getDataTable(request, response);
		} else if (request.getParameter("process_type").equals(
				"getReceiveDetail")) {
			getReceiveDetail(request, response);
		}

	}

	@SuppressWarnings("unchecked")
	public void getReceiveDetail(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String vaSerialNumber = request.getParameter("pnSerialNumber");
		Database db = new Database();
		RcTransDDAO voRcTransDDAO = new RcTransDDAO(db);
		PrintWriter voOut = response.getWriter();
		DecimalFormat voFormatter = new DecimalFormat("#,###,##0.00");
		List<Map<String, Object>> voList = null;
		Map<String, Object> voMap = null;
		voList = voRcTransDDAO.findRcTransDBySerialNumber(vnSiteId,
				vaSerialNumber);

		String vaHtml = "";
		String vaActive = "";
		String vaSeq = "";
		String vaDesCription = "";
		double vnWaterCharge = 0;
		double vnWaterFee = 0;
		double vaVatAmount = 0;
		double vnSumWaterCharge = 0;
		double vnGarbageCharge = 0;
		double vnWastewaterCharge = 0;
		double vnOtherCharge = 0;
		double vnSubTotalAmount = 0;
		double vnPenalty = 0;
		double vnTotalVatAmount = 0;
		double vnTotalSumWaterCharge = 0;
		double vnTotalGarbageCharge = 0;
		double vnTotalWastewaterCharge = 0;
		double vnTotalOtherCharge = 0;
		double vnTotalAmount = 0;
		double vnBillAmount = 0;
		if (voList.get(0).get("RECEIVE_CODE").equals("21")) {

			vaHtml += "<table class=\"table-list\">";
			vaHtml += "<tr>";
			vaHtml += "<th width=\"5%\">ลำดับ</th>";
			vaHtml += "<th width=\"15%\">รายละเอียด</th>";
			vaHtml += "<th width=\"7%\">ค่าน้ำ</th>";
			vaHtml += "<th width=\"7%\">ค่าบริการ</th>";
			vaHtml += "<th width=\"7%\">ค่าภาษี</th>";
			vaHtml += "<th width=\"9%\">รวมค่าน้ำ</th>";
			vaHtml += "<th width=\"7%\">ค่าขยะ</th>";
			vaHtml += "<th width=\"8%\">ค่าบำบัดน้ำเสีย</th>";
			vaHtml += "<th width=\"7%\">ค่าอื่นๆ</th>";
			vaHtml += "<th width=\"8%\">รวมทั้งหมด</th>";
			vaHtml += "</tr>";

			for (int i = 0; i < voList.size(); i++) {
				voMap = voList.get(i);
				if (i % 2 == 0) {
					vaActive = "odd";
				} else {
					vaActive = "even";
				}
				if (voMap.get("SEQ") != null) {
					vaSeq = voMap.get("SEQ").toString();
				}
				if (voMap.get("DESCRIPTION") != null) {
					vaDesCription = voMap.get("DESCRIPTION").toString();
				}
				if (voMap.get("WATER_CHARGE") != null) {
					vnWaterCharge = Double.parseDouble(voMap.get("WATER_CHARGE")
							.toString());
				}
				if (voMap.get("WATER_FEE") != null) {
					vnWaterFee = Double.parseDouble(voMap.get("WATER_FEE")
							.toString());
				}
				if (voMap.get("VAT_AMOUNT") != null) {
					vaVatAmount = Double.parseDouble(voMap.get("VAT_AMOUNT")
							.toString());
				}
				if (voMap.get("GARBAGE_CHARGE") != null) {
					vnGarbageCharge = Double.parseDouble(voMap.get(
							"GARBAGE_CHARGE").toString());
				}
				if (voMap.get("WASTEWATER_CHARGE") != null) {
					vnWastewaterCharge = Double.parseDouble(voMap.get(
							"WASTEWATER_CHARGE").toString());
				}
				if (voMap.get("OTHER_CHARGE") != null) {
					vnOtherCharge = Double.parseDouble(voMap.get("OTHER_CHARGE")
							.toString());
				}
				if (voMap.get("PENALTY") != null) {
					vnPenalty = Double.parseDouble(voMap.get("PENALTY")
							.toString());
				}
				vnSumWaterCharge = vnWaterCharge + vnWaterFee + vaVatAmount;
				vnTotalVatAmount += vaVatAmount;
				vnTotalSumWaterCharge += vnSumWaterCharge;
				vnTotalGarbageCharge += vnGarbageCharge;
				vnTotalWastewaterCharge += vnWastewaterCharge;
				vnTotalOtherCharge += vnOtherCharge;

				vnSubTotalAmount = vnSumWaterCharge + vnGarbageCharge
						+ vnWastewaterCharge + vnOtherCharge;
				vnTotalAmount += vnSubTotalAmount;

				vaHtml += "<tr class=\"" + vaActive + "\">";
				vaHtml += "<td>" + vaSeq + "</td>";
				vaHtml += "<td>" + vaDesCription + "</td>";
				vaHtml += "<td style=\"text-align: right\">"
						+ voFormatter.format(vnWaterCharge) + "</td>";
				vaHtml += "<td style=\"text-align: right\">"
						+ voFormatter.format(vnWaterFee) + "</td>";
				vaHtml += "<td style=\"text-align: right\" class=\"highlight-blue\">"
						+ voFormatter.format(vaVatAmount) + "</td>";
				vaHtml += "<td style=\"text-align: right\" class=\"highlight-blue\">"
						+ voFormatter.format(vnSumWaterCharge) + "</td>";
				vaHtml += "<td style=\"text-align: right\">"
						+ voFormatter.format(vnGarbageCharge) + "</td>";
				vaHtml += "<td style=\"text-align: right\">"
						+ voFormatter.format(vnWastewaterCharge) + "</td>";
				vaHtml += "<td style=\"text-align: right\">"
						+ voFormatter.format(vnOtherCharge) + "</td>";
				vaHtml += "<td style=\"text-align: right\" class=\"highlight-blue\">"
						+ voFormatter.format(vnSubTotalAmount) + "</td>";
				vaHtml += "</tr>";

			}

			vnSubTotalAmount = vnTotalSumWaterCharge + vnTotalGarbageCharge
					+ vnTotalWastewaterCharge + vnTotalOtherCharge;

			vnTotalAmount += vnPenalty;
			vaHtml += "<tr>";
			vaHtml += "<td colspan=\"4\" style=\"text-align: right\">รวม</td>";
			vaHtml += "<td style=\"text-align: right\" class=\"highlight-blue-2\">"
					+ voFormatter.format(vnTotalVatAmount) + "</td>";
			vaHtml += "<td style=\"text-align: right\" class=\"highlight-blue-2\">"
					+ voFormatter.format(vnTotalSumWaterCharge) + "</td>";
			vaHtml += "<td style=\"text-align: right\">"
					+ voFormatter.format(vnTotalGarbageCharge) + "</td>";
			vaHtml += "<td style=\"text-align: right\">"
					+ voFormatter.format(vnTotalWastewaterCharge) + "</td>";
			vaHtml += "<td style=\"text-align: right\">"
					+ voFormatter.format(vnTotalOtherCharge) + "</td>";
			vaHtml += "<td style=\"text-align: right\" class=\"highlight-blue-2\">"
					+ voFormatter.format(vnSubTotalAmount) + "</td>";
			vaHtml += "</tr>";

			vaHtml += "<tr>";
			vaHtml += "<td colspan=\"9\" style=\"text-align: right\">";
			vaHtml += "<input type=\"text\" value=\"ค่าปรับ\" size=\"10\"style=\"text-align: right; padding: 3px\"disabled=\"disabled\" /></td>";
			vaHtml += "<td style=\"text-align: right\" class=\"highlight-blue-2\">"
					+ voFormatter.format(vnPenalty) + "</td>";
			vaHtml += "</tr>";

			vaHtml += "<tr>";
			vaHtml += "<td colspan=\"9\" style=\"text-align: right\">รวมทั้งหมด</td>";
			vaHtml += "<td style=\"text-align: right; font-size: 1.6em\"";
			vaHtml += "class=\"highlight-blue-2\">"
					+ voFormatter.format(vnTotalAmount) + "</td>";
			vaHtml += "</tr>";
		} else {

			vaHtml += "<table class=\"table-list\">";
			vaHtml += "<tr>";
			vaHtml += "<th width=\"10%\">ลำดับที่</th>";
			vaHtml += "<th width=\"40%\">รายการ</th>";
			vaHtml += "<th width=\"15%\">จำนวน</th>";
			vaHtml += "<th width=\"15%\">ภาษี</th>";
			vaHtml += "<th width=\"20%\">จำนวนเงินรวม</th>";
			vaHtml += "</tr>";
			for (int i = 0; i < voList.size(); i++) {
				voMap = voList.get(i);
				if (i % 2 == 0) {
					vaActive = "odd";
				} else {
					vaActive = "even";
				}
				if (voMap.get("SEQ") != null) {
					vaSeq = voMap.get("SEQ").toString();
				}
				if (voMap.get("DESCRIPTION") != null) {
					vaDesCription = voMap.get("DESCRIPTION").toString();
				}
				if (voMap.get("VAT_AMOUNT") != null) {
					vaVatAmount = Double.parseDouble(voMap.get("VAT_AMOUNT")
							.toString());
				}
				if (voMap.get("BILL_AMOUNT") != null) {
					vnBillAmount = Double.parseDouble(voMap.get("BILL_AMOUNT").toString());
				}
				vnTotalAmount += vnBillAmount;
				vaHtml += "<tr class=\""+vaActive+"\">";
				vaHtml += "<td>"+vaSeq+"</td>";
				vaHtml += "<td style=\"text-align:left\">"+vaDesCription+"</td>";
				vaHtml += "<td style=\"text-align:right\">"+voFormatter.format(vnBillAmount - vaVatAmount)+"</td>";
				vaHtml += "<td style=\"text-align:right\">"+voFormatter.format(vaVatAmount)+"</td>";
				vaHtml += "<td style=\"text-align:right\" class=\"highlight-blue\">"+voFormatter.format(vnBillAmount)+"</td>";
				vaHtml += "</tr>";
				
			}

			vaHtml += "<tr>";
			vaHtml += "<td colspan=\"4\" style=\"text-align:right\">รวม</td>";
			vaHtml += "<td style=\"text-align:right\" class=\"highlight-blue-2\">"+voFormatter.format(vnTotalAmount)+"</td>";
			vaHtml += "</tr>";

			vaHtml += "</table>";

		}

		vaHtml += "</table>";
		JSONObject voObject = new JSONObject();
		voObject.put("ReceiveDetailTable", vaHtml);
		
		db.close();
		voOut.print(voObject.toJSONString());

	}

	@SuppressWarnings("unchecked")
	public void getDataTable(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String vaSerialNumber = request.getParameter("sSearch_0").trim();
		String vaAccount = request.getParameter("sSearch_1").trim();
		String vaStatus = request.getParameter("sSearch_2").trim();
		boolean vbSearch = false;
		if (!request.getParameter("sSearch_0").equals("")
				|| !request.getParameter("sSearch_1").equals("")) {
			vbSearch = true;
		}
		if (vbSearch == false) {
			vaSerialNumber = "-1";
			vaAccount = "-1";
		}

		String[] vaColumnsASC = { "receive_date ASC , receive_time ASC",
				"serial_number ASC", "receive_date ASC , receive_time ASC",
				"name ASC", "gross_amount ASC" };
		String[] vaColumnsDESC = { "receive_date DESC , receive_time DESC",
				"serial_number DESC", "receive_date DESC , receive_time DESC",
				"name DESC", "gross_amount DESC" };

		String vaSortColumn = null;
		int vnStart = Integer.parseInt(request.getParameter("iDisplayStart")); // 0
		int vnAmount = Integer.parseInt(request.getParameter("iDisplayLength")); // 10
		int vnSortColumn = Integer.parseInt(request.getParameter("iSortCol_0")); // 0,
																					// 1,
																					// 2,
																					// 3
		String vaSortDirection = request.getParameter("sSortDir_0");

		if (vaSortDirection.equals("asc")) {
			vaSortColumn = vaColumnsASC[vnSortColumn];
		}
		if (vaSortDirection.equals("desc")) {
			vaSortColumn = vaColumnsDESC[vnSortColumn];
		}
		Database db = new Database();
		RcTransMDAO voRcTransMDAO = new RcTransMDAO(db);
		PrintWriter voOut = response.getWriter();
		List<Map<String, Object>> voList = null;
		Map<String, Object> voMap = null;

		int pnEnd = vnStart + vnAmount;

		int vnTotalRecords = voRcTransMDAO
				.getCountAllRcTransMBySerialNumberAndAccount(vnSiteId,
						vaSerialNumber, vaAccount, vaStatus, vaSortColumn);
		int vnTotalDisplayRecords = 0;
		if (vnAmount == -1) {
			voList = voRcTransMDAO
					.findAllRcTransMBySerialNumberAndAccount(vnSiteId,
							vaSerialNumber, vaAccount, vaStatus, vaSortColumn);
			vnTotalDisplayRecords = vnTotalRecords;
		} else {
			voList = voRcTransMDAO.findRcTransMBySerialNumberAndAccount(
					vnSiteId, vaSerialNumber, vaAccount, vaStatus,
					vaSortColumn, vnStart, pnEnd);
			vnTotalDisplayRecords = voRcTransMDAO
					.getCountRcTransMBySerialNumberAndAccount(vnSiteId,
							vaSerialNumber, vaAccount, vaStatus, vaSortColumn);
		}
		JSONObject voObject = new JSONObject();
		JSONArray voListData = new JSONArray();
		JSONArray voArray = new JSONArray();
		String vaAccount2 = "";
		String vaMeterSerialNumber = "";
		String vaName = "";
		String vaCustomerDiscription = "";
		String vaAddress = "";
		CustomerDAO voCustomerDAO = new CustomerDAO(db);
		AddressDAO voAddressDAO = new AddressDAO(db);
		if (voList.size() != 0) {

			vaAccount = voList.get(0).get("ACCOUNT").toString();
			voMap = voCustomerDAO.getCustomer(vnSiteId, vaAccount);

			if (voMap != null) {

				String paProvince = (String) voMap.get("PROVINCE_CODE");
				String paDistrict = (String) voMap.get("DISTRICT_CODE");
				String paCity = (String) voMap.get("CITY_CODE");
				String postCode = "";
				if (voMap.get("ACCOUNT") == null) {
					vaAccount2 = "";
				} else {
					vaAccount2 = (String) voMap.get("ACCOUNT");
				}
				if (voMap.get("METER_SERIAL_NUMBER") == null) {
					vaMeterSerialNumber = "";
				} else {
					vaMeterSerialNumber = (String) voMap
							.get("METER_SERIAL_NUMBER");
				}
				if (voMap.get("NAME") == null) {
					vaName = "";
				} else {
					vaName = (String) voMap.get("NAME");
				}
				if (voMap.get("DESCRIPTION") == null) {
					vaCustomerDiscription = "";
				} else {
					vaCustomerDiscription = (String) voMap.get("DESCRIPTION");
				}
				if (voMap.get("POST_CODE") == null) {
					postCode = "";
				} else {
					postCode = (String) voMap.get("POST_CODE");
				}
				vaAddress = voMap.get("HOME_NUMBER")
						+ " "
						+ voMap.get("ADDRESS")
						+ ""
						+ " "
						+ voAddressDAO.getDistrictName(paProvince, paDistrict)
						+ " "
						+ ""
						+ voAddressDAO.getCityName(paProvince, paDistrict,
								paCity) + " " + ""
						+ voAddressDAO.getProvinceName(paProvince) + " "
						+ postCode;
				vaAddress = vaAddress.replace("null", "");
			}

			for (int i = 0; i < voList.size(); i++) {
				voArray = new JSONArray();
				voMap = voList.get(i);
				voArray.add((i + 1));
				if (voMap.get("SERIAL_NUMBER") != null) {
					voArray.add(voMap.get("SERIAL_NUMBER").toString());
				} else {
					voArray.add("");
				}
				if (voMap.get("RECEIVE_DATE") != null
						&& voMap.get("RECEIVE_TIME") != null) {
					voArray.add(JDate.showDate(voMap.get("RECEIVE_DATE")
							.toString())
							+ " "
							+ JDate.showTime(voMap.get("RECEIVE_TIME")
									.toString()));
				} else {
					voArray.add("");
				}
				String vaEmployeeName = voMap.get("NAME").toString();
				voArray.add(vaEmployeeName.replace("null", ""));
				voArray.add(voMap.get("GROSS_AMOUNT").toString());
				if (voMap.get("STATUS") == null) {
					voArray.add("รับเงิน");
				} else {
					voArray.add("ยกเลิก");

				}

				JSONArray voCustomer = new JSONArray();
				voCustomer.add(vaAccount2);
				voCustomer.add(vaMeterSerialNumber);
				voCustomer.add(vaName);
				voCustomer.add(vaCustomerDiscription);
				voCustomer.add(vaAddress);
				if (voMap.get("SERIAL_NUMBER") != null) {
					voCustomer.add(voMap.get("SERIAL_NUMBER").toString());
				} else {
					voCustomer.add("");
				}
				voArray.add(voCustomer);
				voListData.add(voArray);
			}
		}

		voObject.put("iTotalRecords", vnTotalRecords);
		voObject.put("iTotalDisplayRecords", vnTotalDisplayRecords);
		voObject.put("aaData", voListData);
		
		db.close();
		voOut.print(voObject.toJSONString());

	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

}
